﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;

namespace Mindfor.Web.Data
{
	/// <summary>
	/// Provides extensions functions to query mail.
	/// </summary>
	public static class QueryMailExtensions
	{
		/// <summary>
		/// Returns mail queue items that was not send. Items sorted by date from old to new ones.
		/// </summary>
		/// <param name="maxCount">Maximum count of items to return. Null to return all.</param>
		/// <returns>Mail queue items that was not send.</returns>
		public static IQueryable<MailQueue> GetWaitingQueueItems(this IQueryable<MailQueue> mailQueue, int? maxCount = null)
		{
			IQueryable<MailQueue> q = mailQueue
				.Where(r => r.SendDate == null)
				.OrderBy(r => r.CreateDate)
				.Select(r => (MailQueue)r);
			return maxCount == null ? q : q.Take(maxCount.Value);
		}

		/// <summary>
		/// Returns mail template type by name and module name. If not found returns null.
		/// </summary>
		/// <param name="name">Template type name to search.</param>
		/// <param name="moduleName">Template module name to search.</param>
		public static MailTemplateType Get(this IQueryable<MailTemplateType> templateTypes, string typeName, string moduleName)
		{
			return templateTypes.FirstOrDefault(r => r.Name == typeName && r.ModuleName == moduleName);
		}

		/// <summary>
		/// Returns mail template by type name, module name and language. If not found returns null.
		/// </summary>
		/// <param name="name">Template type name to search.</param>
		/// <param name="moduleName">Template module name to search.</param>
		/// <param name="language">Template language.</param>
		public static MailTemplate Get(this IQueryable<MailTemplate> templates, string typeName, string moduleName, Language language)
		{
			return templates.FirstOrDefault(r => r.Type.Name == typeName && r.Type.ModuleName == moduleName && r.Language == language);
		}
	}
}
